const logger = require('log4js').getLogger()
const Wechat = require('../util/Wechat')

var servers = []

setInterval(() => {
	var now = new Date().getTime()
	for (var i = 0; i < servers.length; i++) {
		for (var j = 0; j < servers[i].length; j++) {
			if (servers[i][j].addTime + 120 * 1000 < now) {
				var content = servers[i][j].url + '失联'
                require('../mng/pushMng').push(content)
				servers[i].splice(j, 1)
				j--
			}
		}
	}
}, 1000 * 60)

exports.add = obj => {
	if (!obj || !obj.url || !obj.priority)
		return

	for (var i = 0; i < servers.length; i++) {
		for (var j = 0; j < servers[i].length; j++) {
			if (servers[i][j].url == obj.url) {
				if (i == obj.priority) {
					servers[i][j].addTime = new Date().getTime()
					return
				}
				servers[i].splice(j, 1)
			}
		}
	}

	logger.debug('[' + __filename + ':' + __line + ']', JSON.stringify(obj))

	while (obj.priority >= servers.length)
		servers.push([])
	servers[obj.priority].push({
		url: obj.url,
		addTime: new Date().getTime()
	})
}

exports.get = (exclude) => {
	exclude = exclude || []
	for (var i = 0; i < servers.length; i++) {
		if (servers[i].length > 0) {
			var idx = require('../../lib/random')(0, servers[i].length - 1)
			for (var j = 0; j < servers[i].length; j++) {
				var url = servers[i][(idx + j) % servers[i].length].url
				if (exclude.indexOf(url) == -1) {
					return url
				}
			}
		}
	}
	return null
}

class Iterator {

	constructor() {
		this.priority = 0;
		this.idx = -1;
	}

	next() {
		// logger.debug('[' + __filename + ':' + __line + ']', this.priority, this.idx, JSON.stringify(servers))

		if (this.priority >= servers.length)
			return null

		for (this.idx++; this.idx < servers[this.priority].length; this.idx++)
			return servers[this.priority][this.idx].url

		for (this.priority++; this.priority < servers.length; this.priority++) {
			for (this.idx = 0; this.idx < servers[this.priority].length; this.idx++)
				return servers[this.priority][this.idx].url
		}

		return null
	}
}

exports.Iterator = Iterator